package com.zingrow.web.customer.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.zip.DataFormatException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.DataFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.base.Splitter;
import com.idaycrm.idaybase.utils.JsonUtils;
import com.idaycrm.idaybase.utils.JsonUtils.JsonResult;
import com.zingrow.common.ReturnStandardDataFormat;
import com.zingrow.common.utils.CommonUtils;
import com.zingrow.common.utils.EncodingUtils;
import com.zingrow.common.utils.PageView;
import com.zingrow.common.utils.StringUtil;
import com.zingrow.common.utils.OptClass;
import com.zingrow.web.base.CodeMsg;
import com.zingrow.web.base.controller.BaseController;
import com.zingrow.web.base.enums.Menu;
import com.zingrow.web.base.enums.Operation;
import com.zingrow.web.configure.iformation.model.Iformation;
import com.zingrow.web.configure.iformation.service.IIformationService;
import com.zingrow.web.configure.iformation.service.impl.IformationService;
import com.zingrow.web.customer.mapper.GroupMapper;
import com.zingrow.web.customer.model.Group;
import com.zingrow.web.customer.model.GroupScheme;
import com.zingrow.web.customer.service.IGroupSchemeService;
import com.zingrow.web.customer.service.IGroupService;
import com.zingrow.web.report.model.RptModel;
import com.zingrow.web.report.model.RptModuleInfo;
import com.zingrow.web.report.service.IRptModelService;
import com.zingrow.web.report.service.IRptModuleService;
import com.zingrow.web.support.operate.model.OptRecord;
import com.zingrow.web.support.operate.service.IOptRecordService;
import com.zingrow.web.user.mapper.UserMapper;
import com.zingrow.web.user.model.ActiveUser;
import com.zingrow.web.user.model.User;
import com.zingrow.web.user.model.UserPermission;
import com.zingrow.web.user.service.IPermissionService;
import com.zingrow.web.user.service.IUserService;

@Controller
@RequestMapping(value = "/group/", produces = "application/json;charset=UTF-8")
public class GroupController extends BaseController {

	@Autowired
	private IGroupService groupService;
	@Autowired
	private IGroupSchemeService groupSchemeService;
	@Autowired
	private IOptRecordService optRecordService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IRptModuleService rptModuleService;
	@Autowired
	private IRptModelService rptModelService;
	@Autowired
	private IIformationService iformationService; 
	@Autowired
	private UserMapper usermapper;
	@Autowired
	private IPermissionService permissionService;
	@Autowired
	private IOptRecordService ioptRecordService;
	@Autowired
	private IIformationService iiformationService;



	/**
	 * 查找所有组织
	 * 
	 * @param request
	 * @param pageIndex
	 * @param pageSize
	 * @param groupName
	 * @param groupBrie
	 * @return
	 */
	@RequestMapping("select")
	@ResponseBody
	public String select(HttpServletRequest request, Integer pageIndex, Integer pageSize, String groupName,
			String groupBrie) {
		List<Group> returnList = new ArrayList<>();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				returnList);
		PageView pageView = null;
		if (null!=groupName && !"".equals(groupName)) {
			groupName = EncodingUtils.fixUrlParamEncoding(request, groupName);
		}
		if (null!=groupBrie && !"".equals(groupBrie)) {
			groupBrie = EncodingUtils.fixUrlParamEncoding(request, groupBrie);
		}


		try {
			
			if (null==pageIndex || pageIndex <= 0) {
				pageIndex = 1;
			}
			if (null==pageSize || pageSize <= 0) {
				pageSize = 10;
			}
			pageView = new PageView(pageSize, pageIndex);
			returnList = groupService.select(groupName, groupBrie, pageView);

		} catch (Exception e) {
			log.error("根据参数查询用户异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"根据参数查询用户异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(returnList);
			return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
		}
		//操作日志
		ActiveUser opuser = getUser(request);//获取操作用户
		OptRecord s = new OptClass().group_query(opuser,Menu.Customerconfiguration.toString(),
				Menu.group.toString(),Operation.query.toString(),groupName,groupBrie);
		if(s.getOptName()!="null")
		ioptRecordService.insert(s);
		// 成功
		standardData.setReturnData(returnList);
		//获取图片显示根路径
		String basepath=request.getRequestURL().toString();
		String[] sd = basepath.split("HandleAdmin");
		basepath="";
		basepath= sd[0]+"imageDir\\";
		standardData.setBasePath(basepath);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		standardData.setTotalPages(pageView.getPageCount());
		standardData.setTotalRecords(pageView.getRowCount());
		return JsonUtils.toString(standardData, JsonResult.STRING_AS_NULL);
	}

	/**
	 * 根据组织id查询下面所有的方案id
	 * 
	 * @param request
	 * @param pageIndex
	 * @param pageSize
	 * @param groupName
	 * @param groupBrie
	 * @return
	 */
	@RequestMapping("selectgroupid")
	@ResponseBody
	public String selectgroupid(HttpServletRequest request, String groupId) {
		List<Group> returnList = new ArrayList<>();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				returnList);
		try {
			// 判断参数合法性
			if (CommonUtils.isStrNull(groupId)) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}

			returnList = groupService.selectgroupid(Integer.parseInt(groupId));

		} catch (Exception e) {
			log.error("根据参数查询用户异常");
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(returnList);
			return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
		}
		// 成功
		standardData.setReturnData(returnList);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		return JsonUtils.toString(standardData, JsonResult.STRING_AS_NULL);
	}

	/**
	 * 查找所有组织
	 * 
	 * @param request
	 * @param pageIndex
	 * @param pageSize
	 * @param groupName
	 * @param groupBrie
	 * @return
	 */
	@RequestMapping("selectAll")
	@ResponseBody
	public String selectAll(HttpServletRequest request) {
		List<Group> returnList = new ArrayList<>();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,returnList);
        try {

			returnList = groupService.selectAll();

		} catch (Exception e) {
			log.error("根据参数查询用户异常");
			log.error(e, e.fillInStackTrace());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(returnList);
			return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
		}
		// 成功
		standardData.setReturnData(returnList);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		return JsonUtils.toString(standardData, JsonResult.STRING_AS_NULL);
	}

	/**
	 * 增加组织
	 * 
	 * @param request
	 * @param group
	 * @return
	 */
	@RequestMapping("addGroup")
	@ResponseBody
	public String addGroup(HttpServletRequest request, Group group,
			@RequestParam(value = "file", required = false) MultipartFile file) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		try {			
			if (CommonUtils.isStrNull(group.getGroupName()) || CommonUtils.isStrNull(group.getGroupBrie())
					|| group.getGroupName().length() > 100 || group.getGroupBrie().length() > 50
					|| group.getGroupSketch().length() > 1000) {
				// 判断传入参数合法性
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (file!=null) {
			// 获得物理路径webapp所在路径
			String path = "";
			String pathRoot=getImageRootPath(request);
			//String pathRoot = request.getSession().getServletContext().getRealPath("");
			// 生成uuid作为文件名称
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			// 获得文件类型
			String fileName = file.getOriginalFilename();// 获取文件全名称
			String contentType = file.getContentType();
			String type = fileName.indexOf(".") != -1? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
			if ("PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())
					|| "JPEG".equals(type.toUpperCase()) || "BMP".equals(type.toUpperCase())) {
				// 获得文件后缀名称
				//String imageName = contentType.substring(contentType.indexOf("/") + 1);
				File file1 = new File(pathRoot  + "Picture");
				// 如果文件夹不存在则创建
				if (!file1.exists() && !file1.isDirectory())
					file1.mkdir();
				path = "Picture/" + uuid + "." + "png";
				//放入图片
				file.transferTo(new File(pathRoot + path));
				//图片按照132*132压缩
				zoomImage(pathRoot + path,pathRoot + path,132,132);
				// 写入图片的相对路径
				String groupImage = "Picture/" + uuid + "." + "png";			
				group.setGroupImage(groupImage);
			} else {
				// 判断传入图片的格式合法性
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
				}
			}	
			else
			{   //新增无头像默认为空显示默认头像
				group.setGroupImage("");
			}
				if (null!=group.getGroupName() && !"".equals(group.getGroupName())) {
					group.setGroupName(EncodingUtils.fixUrlParamEncoding(request, group.getGroupName()));
				}
				if (null!=group.getGroupBrie() && !"".equals(group.getGroupBrie())) {
					group.setGroupBrie(EncodingUtils.fixUrlParamEncoding(request, group.getGroupBrie()));
				}
				if (null!=group.getGroupSketch() && !"".equals(group.getGroupSketch())) {
					group.setGroupSketch(EncodingUtils.fixUrlParamEncoding(request, group.getGroupSketch()));
				}
				if (groupService.querySameByGroup(group.getGroupName(), null)) {
					// 检测到有除此信息之外的同名数据
					standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
					standardData.setReturnMessage("新增失败，已存在其他相同组织！");
					return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
				}
				group.setInsertTime(new Date());
				if (groupService.addGroup(group)) {
					
					//操作日志
					ActiveUser opuser = getUser(request);//获取操作用户
					OptRecord s = new OptClass().group_add(group,opuser,Menu.Customerconfiguration.toString(),
							Menu.group.toString(),Operation.insert.toString());
					if(s.getOptName()!="null")
					ioptRecordService.insert(s);				
					standardData.setReturnCode(CodeMsg.CODE_OK);
					standardData.setReturnMessage(CodeMsg.MSG_OK);
					return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
				}
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");

		} catch (Exception e) {
			log.error("添加用户异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"添加用户异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_ERROR);
			standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
		}
	}

	/**
	 * 修改组织
	 */
	@RequestMapping("modifyGroup")
	@ResponseBody
	public String modify(HttpServletRequest request, Group group,
			@RequestParam(value = "file", required = false) MultipartFile file) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		try {
			Group Originalgroup=groupService.selectgruopgroupid(group.getGroupId());
			if (CommonUtils.isStrNull(group.getGroupName()) || CommonUtils.isStrNull(group.getGroupBrie())
					|| group.getGroupName().length() > 100 || group.getGroupBrie().length() > 50
					|| group.getGroupSketch().length() > 1000) {
				// 判断传入参数合法性
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (file!=null) {
				String path = "";
				String pathRoot=getImageRootPath(request);
				//String pathRoot = request.getSession().getServletContext().getRealPath("");
				// 生成uuid作为文件名称
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				// 获得文件类型
				String fileName = file.getOriginalFilename();// 获取文件全名称
				String contentType = file.getContentType();
				String type = fileName.indexOf(".") != -1
						? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
				if ("PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())
						|| "JPEG".equals(type.toUpperCase()) || "BMP".equals(type.toUpperCase())) {
					// 获得文件后缀名称
					//String imageName = contentType.substring(contentType.indexOf("/") + 1);
					File file1 = new File(pathRoot + "Picture");
					// 如果文件夹不存在则创建
					if (!file1.exists() && !file1.isDirectory())
						file1.mkdir();
					path = "Picture/" + uuid + "." + "png";
					//放入图片
					file.transferTo(new File(pathRoot + path));
					//图片按照132*132压缩
					zoomImage(pathRoot + path,pathRoot + path,132,132);
					// 写入图片的相对路径
					String groupImage = "Picture/" + uuid + "." + "png";
					// 删除之前的图片
					File dele = new File(pathRoot+group.getGroupImage());
					dele.delete();
					group.setGroupImage(groupImage);
				} else {
					// 判断传入图片合法性
					standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
					standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
					return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
				}

			} else
			{
				group.setGroupImage(group.getGroupImage());
			}
			
			if (null!=group.getGroupName() && !"".equals(group.getGroupName())) {
				group.setGroupName(EncodingUtils.fixUrlParamEncoding(request, group.getGroupName()));
			}
			if (null!=group.getGroupBrie() && !"".equals(group.getGroupBrie())) {
				group.setGroupBrie(EncodingUtils.fixUrlParamEncoding(request, group.getGroupBrie()));
			}
			if (null!=group.getGroupSketch() && !"".equals(group.getGroupSketch())) {
				group.setGroupSketch(EncodingUtils.fixUrlParamEncoding(request, group.getGroupSketch()));
			}
			if (groupService.querySameByGroup(group.getGroupName(), group.getGroupId())) {
				// 检测到有除此信息之外的同名数据
				standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
				standardData.setReturnMessage("修改失败，已存在其他相同组织！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			group.setUpdateTime(new Date());
			// 查询该组织拥有的方案数
			int count = groupSchemeService.selectByGroupId(group.getGroupId());
			// 查询组织拥有的用户数
			int count2 = userService.selectByGroupId(group.getGroupId());
			if (count > group.getSchemeNum()) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
				standardData.setReturnMessage("当前组织拥有方案数大于" + group.getSchemeNum());
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (count2 > group.getUserNum()) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
				standardData.setReturnMessage("当前组织拥有用户数大于" + group.getUserNum());
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (groupService.updateGroup(group)) {
				//操作日志
				ActiveUser opuser = getUser(request);//获取操作用户
				OptRecord s = new OptClass().group_update(group,Originalgroup,opuser,Menu.Customerconfiguration.toString(),
						Menu.group.toString(),Operation.update.toString());
				if(s.getOptName()!="null")
				ioptRecordService.insert(s);			
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			}

		} catch (Exception e) {
			log.error("根据参数修改用户异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"根据参数修改用户异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_ERROR);
			standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 删除组织
	 */
	@ResponseBody
	@RequestMapping("delGroup")
	public String delGroup(HttpServletRequest request, String groupId, String groupName) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		try {
			if (null!=groupName && !"".equals(groupName)) {
				groupName = EncodingUtils.fixUrlParamEncoding(request, groupName);
			}
			if (StringUtils.isBlank(groupId)) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			Integer gId = Integer.parseInt(groupId);
			if (groupService.delGroup(gId)) {
				//删除操作成功删除组织图片
				String pathRoot=getImageRootPath(request);
				int gid=Integer.parseInt(groupId);
				User ak = usermapper.selectGroupImage(gid);
				File dele = new File(pathRoot+ak.getGroupImage());
				dele.delete();
				//操作日志
				ActiveUser opuser = getUser(request);//获取操作用户
				OptRecord s = new OptClass().group_delete(opuser,Menu.Customerconfiguration.toString(),
						Menu.group.toString(),Operation.delete.toString(),groupName);
				if(s.getOptName()!="null")
				ioptRecordService.insert(s);		
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			}
		} catch (Exception e) {
			log.error("根据参数删除用户异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"根据参数删除用户异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_ERROR);
			standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
	
	/**
	 * 批量删除
	 * 
	 * @param request
	 * @return
	 *//*
	@RequestMapping("delGroups")
	@ResponseBody
	public String delGroups(HttpServletRequest request, String gId) {
		String idsa="126,127,128,129";
		String[] returnList = new String[100];
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				returnList);
		try {
			if (idsa != null && !"".equals(idsa)) {
				returnList = idsa.split(",");
			}
			for(int i=0;i<returnList.length;i++)
			{
				Integer intgId = Integer.parseInt(returnList[i]);
				if (groupService.delGroup(intgId)) {
					//根据组织ID查询组织名称
					String gname = groupService.selectGroupNameByGroupid(intgId);
					//删除操作成功删除组织图片
					String pathRoot=getImageRootPath(request);
					User ak = usermapper.selectGroupImage(intgId);
					File dele = new File(pathRoot+ak.getGroupImage());
					dele.delete();
					addOptRecode(request, optRecordService, Menu.group.toString(), Operation.delete.toString(), gname);
					// 操作成功
					standardData.setReturnCode(CodeMsg.CODE_OK);
					standardData.setReturnMessage(CodeMsg.MSG_OK);
				} else {
					standardData.setReturnCode(CodeMsg.CODE_ERROR);
					standardData.setReturnMessage(CodeMsg.MSG_ERROR);
				}
			}
		} catch (Exception e) {
			log.error("根据参数删除用户异常");
			log.error(e, e.fillInStackTrace());
			standardData.setReturnCode(CodeMsg.CODE_ERROR);
			standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
*/

	@RequestMapping("selectModelgroupId")
	@ResponseBody
	public String selectModelgroupId(HttpServletRequest request, HttpServletResponse response, Integer groupId,
			String ifmName, String ifmId) {
		List<RptModel> listmodel = new ArrayList<RptModel>();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				listmodel);
		try {
			if (StringUtils.isBlank(ifmId) && null == groupId) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			// 转码
			/*if (StringUtils.isNotBlank(ifmName)) {
				ifmName = EncodingUtils.fixUrlParamEncoding(request, ifmName);
			}*/
			List<String> listifmId = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(ifmId); // 分割方案ID
			List<String> ifmname = new ArrayList<String>();//方案名称集合
			for (String fid : listifmId) { //循环方案ID
				//根据方案ID和组织ID查询报告模板信息
				List<RptModel> model = rptModelService.selectModelgroupId(groupId, Integer.valueOf(fid));
				if (model.size()>0) { //判断
					 Iformation tion = iformationService.queryByID(Integer.valueOf(fid)); //根据方案ID查询方案名称
					 ifmname.add(tion.getIfm_name());
				}
				for (RptModel rptModel : model) {
					listmodel.add(rptModel);
				}
			}
			//报告模板名称集合
			List<String> listname = new ArrayList<String>();
			for (RptModel rptModel : listmodel) { //循环报告模板集合
				listname.add(rptModel.getName());
			}
			//报告模板名称
			String name = StringUtil.toStringjoin(listname);
			//方案名称
			String ifmname2 = StringUtil.toStringjoin(ifmname);
			if (listmodel.size() > 0) {
				standardData.setReturnData(listmodel.size());
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage("该组织中的\"" + ifmname2 + "\"方案已被报告模板" + name + "使用,是否去报告模板列表页解绑方案");
			} else {
				standardData.setReturnData(listmodel.size());
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			}
		} catch (Exception e) {
			log.error("更新异常");
			log.error(e, e.fillInStackTrace());
			standardData.setReturnCode(CodeMsg.CODE_ERROR);
			standardData.setReturnMessage(CodeMsg.MSG_ERROR);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 改变组织方案
	 */
	@ResponseBody
	@RequestMapping("changeGroupScheme")
	public String changeGroupScheme(HttpServletRequest request, String groupId, String gScheme, String groupName,
			String ifmId, String ropeProgramme,Integer rptifmId) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		int[] arr= {14,5,12,4};
		GroupScheme groupScheme = new GroupScheme();	
		Integer mId = null;
		try {
			List<GroupScheme> groups =groupSchemeService.selectgroupid(Integer.parseInt(groupId));
			Integer gId = Integer.parseInt(groupId);
			if (StringUtils.isNotBlank(ifmId)) {
				mId = Integer.parseInt(ifmId);
			}
			List<Integer> list = new ArrayList();
			List<String> ifmlist = new ArrayList<String>();
			String ifmids = "";
			if (CommonUtils.isStrNotNull(gScheme)) {
				list = StringUtil.getStringToList(gScheme);
			}
			// 查询该组织栏目字段具体数值
			Group group = groupService.selectpossess(gId);
			// 查询组织可拥有栏目数
			int count = groupSchemeService.selectiform(list, gId);
			if (list.size() > group.getSchemeNum()) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage("该组织只能拥有" + group.getSchemeNum() + "个栏目数");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			} else {
                //获取该组织原有信息
				List<Iformation> ifa = iformationService.selectcheckalready(gId);
				// 删除原有的数据
				if (groupSchemeService.delGroupScheme(gId)) {
					// 判断组织可拥有栏目数
					if (count <= group.getSchemeNum()) {
						if (list.size() >= 0) {
							if (mId != null && !"".equals(mId)) {
								for (Integer object : list) {
									if (mId.equals(object)) {
										//if(!groupSchemeService.selectByIfmId(object))
										groupScheme.setGroupId(gId);
										groupScheme.setIfmId(object);
										groupScheme.setIfmIsSensitivity(1);
										for(int i=0;i<ifa.size();i++)
										{
										if(object==ifa.get(i).getIfm_id().intValue()){
										groupScheme.setIfmcategory(ifa.get(i).getIfm_category());
										groupScheme.setIfmcategoryName(ifa.get(i).getIfm_categoryName());										
										break;}
										else{groupScheme.setIfmcategory("");
											groupScheme.setIfmcategoryName("");}
										}
										if(ifa.size()==0){groupScheme.setIfmcategory("");
										groupScheme.setIfmcategoryName("");}
										groupSchemeService.insertmg(groupScheme);
										for (int i = 0; i < arr.length; i++) {
										// 根据组织ID和敏感方案ID查询数据
										List<RptModuleInfo> listmodul = rptModuleService.queryGroupIdIfmId(gId,Integer.valueOf(arr[i]));
										//int count3 = rptModuleService.selectBygIdpIdmuId(Integer.valueOf(groupId),Integer.valueOf(arr[i]),mId);
										if (listmodul.size() > 0) {
											// rptModuleService.queryGroupIdmoduleId(gId,Integer.valueOf(arr[i]));
											for (RptModuleInfo rptModuleInfo : listmodul) {
												// 改变了敏感方案，就把之前的敏感方案更改为非敏感方案
												if (null != rptifmId) {
													// 变更之前的敏感方案
													RptModuleInfo rptModule = new RptModuleInfo();
													rptModule.setIsSensitive(0);
													rptModule.setPlanId(rptifmId);
													rptModule.setModelId(rptModuleInfo.getModelId());
													rptModule.setModuleId(rptModuleInfo.getModuleId());
													// 执行修改
													rptModuleService.updateByPrimaryKey(rptModule);
												}
												// 判断敏感方案ID和数据库中的方案ID相同，就把数据库该方案改为敏感方案
												if (rptModuleInfo.getPlanId().equals(mId)) {
													// 变更敏感方案
													RptModuleInfo module = new RptModuleInfo();
													module.setIsSensitive(1);
													module.setPlanId(mId);
													module.setModelId(rptModuleInfo.getModelId());
													module.setModuleId(rptModuleInfo.getModuleId());
													// 执行修改
													rptModuleService.updateByPrimaryKey(module);
												}
											}
										}
									}
								} else {
									//if(!groupSchemeService.selectByIfmId(object))
										groupScheme.setGroupId(gId);
										groupScheme.setIfmId(object);
										groupScheme.setIfmIsSensitivity(0);
										for(int i=0;i<ifa.size();i++)
										{
										if(object==ifa.get(i).getIfm_id().intValue()){
										groupScheme.setIfmcategory(ifa.get(i).getIfm_category());
										groupScheme.setIfmcategoryName(ifa.get(i).getIfm_categoryName());										
										break;}
										else{groupScheme.setIfmcategory("");
											groupScheme.setIfmcategoryName("");}
										}
										if(ifa.size()==0){groupScheme.setIfmcategory("");
										groupScheme.setIfmcategoryName("");}
										groupSchemeService.insertmg(groupScheme);
									
								}
								}
								if (StringUtils.isNotBlank(ropeProgramme)) {
									List<String> ropeProgrammeList = StringUtil.toStringTokenizer(ropeProgramme, ",");
									// 根据组织ID查询用户集合
									List<UserPermission> ulist = userService.selectuIdifmId(Integer.valueOf(groupId));
									if (ulist.size() > 0) {
										// 循环查询到的集合
										for (UserPermission up : ulist) {
											if (StringUtils.isNoneBlank(up.getRopeProgramme())) {
												// 字符串分割
												ifmlist = StringUtil.toStringTokenizer(up.getRopeProgramme(), ",");
												for (int i = 0; i < ifmlist.size(); i++) {
													for (String ropeProgramme1 : ropeProgrammeList) {
														// 调用模板模块删除接口
														// rptModuleService.deleteplanId(Integer.valueOf(ropeProgramme1));
														if (ifmlist.size() > 0) {
															// 判断是否相等，相等删除相等的
															if (ifmlist.get(i).equals(ropeProgramme1)) {
																ifmlist.remove(i);
															}
														}
													}
												}
												// 字符串拼接
												ifmids = StringUtil.toStringjoin(ifmlist);
											}
											up.setRopeProgramme(ifmids);
											// 替换需要删除的方案
											String ropeProgramme1 = up.getRopeProgramme().replace(ropeProgramme, "");
											// 修改用户方案
											userService.updateifmId(ropeProgramme1, up.getUserId());
										}
									}
								}
								//操作日志记录
								ActiveUser opuser = getUser(request);//获取操作用户
								List<List<String>> lista=new ArrayList<List<String>>();
							/*	String[] startlist= new String[50];
								if(groups.size()>0)
								{
									for(int i=0;i<groups.size();i++)
										startlist[i]=groups.get(i).getIfmId().toString();
								}
								String[] endlist=gScheme.split(",");
								List<List<String>> lista=new OptClass().comparearray(startlist,endlist);
								for(int i=0;i<2;i++){	
								List<String> s=new ArrayList<String>();
								if(i==0&&lista.get(0).size()==0){lista.add(s);continue;}
								if(i==1&&lista.get(1).size()==0){lista.add(s);continue;}
								List<Iformation> iformationlist=iiformationService.selectlistId(lista.get(i));
								for(int k=0;k<iformationlist.size();k++)
									s.add(iformationlist.get(k).getIfm_name()+"("+iformationlist.get(k).getIfm_note()+")");
								lista.add(s);}*/
								OptRecord s = new OptClass().group_queryinformation(opuser,Menu.Customerconfiguration.toString()
										,Menu.group.toString(),Operation.updateProinformation.toString(),groupName,lista);
								if(s.getOptName()!=null)
								
								ioptRecordService.insert(s);	
							/*	Iformation b1=iiformationService.queryByID(Integer.parseInt(ifmId));
								Iformation b2=iiformationService.queryByID(rptifmId);
								OptRecord s1 = new OptClass().group_queryinformations(opuser,Menu.Customerconfiguration.toString()
										,Menu.group.toString(),Operation.updateProinformation.toString(),groupName,b1,b2,groups);
								if(s1.getOptName()!=null)
								ioptRecordService.insert(s1);*/
								// 操作成功
								standardData.setReturnCode(CodeMsg.CODE_OK);
								standardData.setReturnMessage(CodeMsg.MSG_OK);
							} else {
								for (Integer object : list) {
									//if(!groupSchemeService.selectByIfmId(object))
									groupScheme.setGroupId(gId);
									groupScheme.setIfmId(object);
									groupScheme.setIfmIsSensitivity(0);
									for(int i=0;i<ifa.size();i++)
									{
									if(object==ifa.get(i).getIfm_id().intValue()){
									groupScheme.setIfmcategory(ifa.get(i).getIfm_category());
									groupScheme.setIfmcategoryName(ifa.get(i).getIfm_categoryName());										
									break;
										}
									else{groupScheme.setIfmcategory("");
										groupScheme.setIfmcategoryName("");}
									}
									if(ifa.size()==0){groupScheme.setIfmcategory("");
									groupScheme.setIfmcategoryName("");}
									groupSchemeService.insertmg(groupScheme);
								}
								if (StringUtils.isNotBlank(ropeProgramme)) {
									List<String> ropeProgrammeList = StringUtil.toStringTokenizer(ropeProgramme, ",");
									// 根据组织ID查询用户集合
									List<UserPermission> ulist = userService.selectuIdifmId(Integer.valueOf(groupId));
									if (ulist.size() > 0) {
										// 循环查询到的集合
										for (UserPermission up : ulist) {
											if (StringUtils.isNoneBlank(up.getRopeProgramme())) {
												// 字符串分割
												ifmlist = StringUtil.toStringTokenizer(up.getRopeProgramme(), ",");
												for (int i = 0; i < ifmlist.size(); i++) {
													for (String ropeProgramme1 : ropeProgrammeList) {
														// 调用模板模块删除接口
														// rptModuleService.deleteplanId(Integer.valueOf(ropeProgramme1));
														if (ifmlist.size() > 0) {
															// 判断是否相等，相等删除相等的
															if (ifmlist.get(i).equals(ropeProgramme1)) {
																ifmlist.remove(i);
															}
														}
													}
												}
												// 字符串拼接
												ifmids = StringUtil.toStringjoin(ifmlist);
											}
											up.setRopeProgramme(ifmids);
											// 替换需要删除的方案ID
											String ropeProgramme1 = up.getRopeProgramme().replace(ropeProgramme, "");
											// 修改用户方案
											userService.updateifmId(ropeProgramme1, up.getUserId());
										}
									}
								}
								/*addOptRecode(request, optRecordService, Menu.group.toString(),
										Operation.update.toString(), groupName);*/
								// 操作成功
								//操作日志记录
								ActiveUser opuser = getUser(request);//获取操作用户
								List<List<String>> lista=new ArrayList<List<String>>();
								/*String[] startlist= new String[50];
								if(groups.size()>0)
								{
									for(int i=0;i<groups.size();i++)
										startlist[i]=groups.get(i).getIfmId().toString();
								}
								String[] endlist=gScheme.split(",");
								List<List<String>> lista=new OptClass().comparearray(startlist,endlist);
								for(int i=0;i<2;i++){	
								List<String> s=new ArrayList<String>();
								if(i==0&&lista.get(0).size()==0){lista.add(s);continue;}
								if(i==1&&lista.get(1).size()==0){lista.add(s);continue;}
								List<Iformation> iformationlist=iiformationService.selectlistId(lista.get(i));
								for(int k=0;k<iformationlist.size();k++)
									s.add(iformationlist.get(k).getIfm_name()+"("+iformationlist.get(k).getIfm_note()+")");
								lista.add(s);}*/
								OptRecord s = new OptClass().group_queryinformation(opuser,Menu.Customerconfiguration.toString()
										,Menu.group.toString(),Operation.updateProinformation.toString(),groupName,lista);
								if(s.getOptName()!=null)
								ioptRecordService.insert(s);
								/*Iformation b1= new Iformation();
								if(ifmId!=null&&!"".equals(ifmId))
								b1=iiformationService.queryByID(Integer.parseInt(ifmId));
								else
								b1=null;
								Iformation b2=iiformationService.queryByID(rptifmId);
								OptRecord s1 = new OptClass().group_queryinformations(opuser,Menu.Customerconfiguration.toString()
										,Menu.group.toString(),Operation.updateProinformation.toString(),groupName,b1,b2,groups);
								if(s1.getOptName()!=null)
								ioptRecordService.insert(s1);*/
								standardData.setReturnCode(CodeMsg.CODE_OK);
								standardData.setReturnMessage(CodeMsg.MSG_OK);
							}
						} else {
							standardData.setReturnCode(CodeMsg.CODE_ERROR);
							standardData.setReturnMessage(CodeMsg.MSG_ERROR);
						}
					} else {
						standardData.setReturnCode(CodeMsg.CODE_ERROR);
						standardData.setReturnMessage("该组织只能拥有" + group.getSchemeNum() + "个栏目数");
						return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
					}
				}
			}
		} catch (Exception e) {
			log.error("根据参数修改组织方案异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"根据参数修改组织方案异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_ERROR);
			standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
		}	
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 查找所有组织简称
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("selectAllName")
	@ResponseBody
	public String selectAllName(HttpServletRequest request, String gName) {
		List<Group> returnList = new ArrayList<>();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				returnList);
		try {

			if (gName != null && !"".equals(gName)) {
				gName = EncodingUtils.fixUrlParamEncoding(request, gName);
			}
			returnList = groupService.selectAllName(gName);
		} catch (Exception e) {
			log.error("查询用户异常");
			log.error(e, e.fillInStackTrace());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(returnList);
			return JsonUtils.toString(standardData, JsonResult.STRING_AS_NULL);
		}
		// 成功
		standardData.setReturnData(returnList);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		return JsonUtils.toString(standardData, JsonResult.STRING_AS_NULL);
	}

	/**
	 * 查找该组织下所选的方案
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("selectGroupScheme")
	@ResponseBody
	public String selectGroupScheme(HttpServletRequest request, Integer pageIndex, Integer pageSize, Integer gId,
			String ifmName, String ifmNote) {
		List<GroupScheme> returnList = new ArrayList<>();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				returnList);
		PageView pageView = null;
		try {
			if (null==pageIndex || pageIndex <= 0) {
				pageIndex = 1;
			}
			if (null==pageSize || pageSize <= 0) {
				pageSize = 10;
			}
			pageView = new PageView(pageSize, pageIndex);
			if (CommonUtils.isObjectNull(gId)) {
				standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
				standardData.setReturnMessage("参数错误");
				return JsonUtils.toString(standardData, JsonResult.STRING_AS_NULL);
			}
			if (null!=ifmName || "".equals(ifmName)) {
				ifmName = EncodingUtils.fixUrlParamEncoding(request, ifmName);
			}
			if (null!=ifmNote || "".equals(ifmNote)) {
				ifmNote = EncodingUtils.fixUrlParamEncoding(request, ifmNote);
			}
			returnList = groupSchemeService.selectBySchemeAll(pageView, gId, ifmName, ifmNote);
		} catch (Exception e) {
			log.error("查询组织方案异常");
			log.error(e, e.fillInStackTrace());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(returnList);
			return JsonUtils.toString(standardData, JsonResult.STRING_AS_NULL);
		}
		// 成功
		standardData.setReturnData(returnList);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		standardData.setTotalPages(pageView.getPageCount());
		standardData.setTotalRecords(pageView.getRowCount());
		return JsonUtils.toString(standardData, JsonResult.STRING_AS_NULL);
	}


	
	// 根据组织ID修改组织报告权限
	@RequestMapping("updateByGroupId")
	@ResponseBody
	public String updateByGroupId(HttpServletRequest request, Group group,String rptRight) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		try {
			if (CommonUtils.isStrNull(group.getRptRight().toString())
					&& CommonUtils.isStrNull(group.getGroupId().toString())) {
				standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
				standardData.setReturnMessage("参数错误");
				return JsonUtils.toString(standardData, JsonResult.STRING_AS_NULL);
			}
			// 修改报告组织权限
			if (groupService.updateByGroupId(group)) {	
				Group groups=groupService.selectgruopgroupid(group.getGroupId());		
				//操作日志
				ActiveUser opuser = getUser(request);//获取操作用户
				OptRecord s = new OptClass().group_queryPresentation(opuser,Menu.Customerconfiguration.toString()
						,Menu.group.toString(),Operation.updatePresentation.toString(),groups.getGroupName(),rptRight);
				if(s.getOptName()!=null)
				ioptRecordService.insert(s);			
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			}
		} catch (Exception e) {
			log.error("查询组织方案异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"查询组织方案异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			return JsonUtils.toString(standardData, JsonResult.STRING_AS_NULL);
		}
		return JsonUtils.toString(standardData, JsonResult.STRING_AS_NULL);
	}
	
	@ExceptionHandler(Exception.class)       
    public String handleException(Exception ex,HttpServletRequest request) {     
        if(ex instanceof org.springframework.web.multipart.MaxUploadSizeExceededException){  
            request.setAttribute("error", "文件超过长度");  
        }  
        ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
     // 判断传入图片的格式合法性
		standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
		standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");

    } 
	
}
